package com.yjj.image.util.service;

import com.luciad.imageio.webp.WebPReadParam;
import com.yjj.demo.common.service.DingTalkMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 *
 *
 * @author yangjiajia
 * @createdAt 2022/8/23 14:17
 */
@Service
public class ImageConvertService {

    @Value("${webp_path}")
    private String webpPath;

    @Autowired
    private DingTalkMessageService dingTalkMessageService;

    private Logger logger = LoggerFactory.getLogger(ImageConvertService.class);

    //@PostConstruct
    public void init() throws Exception {
        logger.info("服务启动");

        Iterator<ImageReader> imageIterator = ImageIO.getImageReadersByMIMEType("image/webp");
        ImageReader imageReader = imageIterator.next();

        File webpFile = new File(webpPath);
        File[] fileList = webpFile.listFiles();
        if (fileList == null || fileList.length == 0) {
            logger.info(String.format("未找到目录,%s", webpPath));
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String str = sdf.format(new Date());
        String jpgPath = System.getProperty("user.dir") + "/jpg_" + str + "/";
        File targetDir = new File(jpgPath);
        if (!targetDir.exists()) {
            boolean createResult = targetDir.mkdir();
            if (!createResult) {
                logger.info("目标文件夹创建失败");
                return;
            }
        }

        logger.info(String.format("webp_path:%s,jpg_path:%s", webpFile, jpgPath));

        int count = 0;
        for (File file : fileList) {
            if (!file.isFile()) {
                continue;
            }
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            if (!suffix.equals(".webp")) {
                continue;
            }

            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);

            // Configure the input on the ImageReader
            imageReader.setInput(new FileImageInputStream(file));

            // Decode the image
            BufferedImage image = imageReader.read(0, readParam);

            // the `png` can use `jpg`
            String newName = fileName.substring(0, fileName.lastIndexOf("."));
            ImageIO.write(image, "jpg", new File(jpgPath + newName + ".jpg"));
            logger.info(String.format("%s转换成功", fileName));
            count ++;
        }

        logger.info(String.format("转换成功,共%d个文件,转换成功%d个", fileList.length, count));

        //Desktop.getDesktop().open(webpFile);
//        String[] cmd = {"explorer.exe", "d://test"};
//        Runtime.getRuntime().exec("cmd /c start explorer " + webpPath);
//        Runtime.getRuntime().exit(0);

        //System.exit(0);
    }

    public void sendMsg(String msg) {
        dingTalkMessageService.sendMsg(msg);
    }
}
